<template>
  <layout-drawer-list v-model:visible="visible" :title="enumModifyType(drawerType)">
    <template #main>
      <div>
        <div></div>
        <vxe-toolbar>
          <template #buttons>
            <a-button type="primary" @click="openDrawer('create')">新增</a-button>
          </template>
          <template #tools></template>
        </vxe-toolbar>
      </div>
      <div class="rd-flex-1">
        <vxe-grid v-bind="gridOptions" :data="tableList">
          <template #modify="{ row }">
            <a-button type="link" size="small" @click="openDrawer('edit', row)">编辑</a-button>
            <a-popconfirm
              title="是否删除该角色？"
              ok-text="删除"
              cancel-text="取消"
              @confirm="onSubmitDelete(row)"
            >
              <a href="#">删除</a>
            </a-popconfirm>
          </template>
          <!-- <template #pager></template> -->
        </vxe-grid>
      </div>
      <div class="rd-box-center">
        <a-pagination
          v-model:current="page"
          v-model:page-size="limit"
          :page-size-options="['10', '20', '50', '100']"
          :total="totalCount"
          showSizeChanger
          showQuickJumper
          @change="changePage"
          @showSizeChange="pageSizeChange"
        >
        </a-pagination>
      </div>
    </template>
    <template #drawer v-if="visible">
      <a-form
        ref="formRef"
        :model="modelRef"
        :rules="rulesRef"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item
          label="专题"
          required
        >
          <a-radio-group v-model:value="modelRef.subjectId" @change="changeSubjectId">
            <a-radio-button v-for="item in ['1', '2']" :key="item" :value="item">{{enumSubjectId(item)}}</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="角色名称"
          name="roleName"
        >
          <a-input placeholder="填写角色名称" v-model:value="modelRef.roleName" />
        </a-form-item>
        <a-form-item
          label="备注"
          name="remark"
        >
          <a-input placeholder="填写备注" v-model:value="modelRef.remark" />
        </a-form-item>
        <a-form-item
          label="授权"
          name="menuIdList"
        >
          <a-tree
            checkable
            :tree-data="tableTree"
            :replaceFields="{ key: 'menuId', title: 'name' }"
            v-model:checkedKeys="modelRef.checkedKeys"
            @check="check"
          >
            <template #title0010><span style="color: #1890ff">sss</span></template>
          </a-tree>
        </a-form-item>
        <div class="rd-box-center">
          <a-button type="primary" @click="onSubmit">提交</a-button>
        </div>
      </a-form>

    </template>
  </layout-drawer-list>
</template>

<script>
import { ref, reactive, onMounted, toRaw } from 'vue'
import { cloneDeep } from 'lodash'
import { Enum } from '@/utils'
import LayoutDrawerList from '@/layout/LayoutDrawerList.vue'
import mainMenuList from '@/composables/system/mainMenuList'
// api
import { fetchRoleList, fetchRoleInfo, fetchRoleCreate, fetchRoleUpdate, fetchRoleDelete } from '@/api'

const { enumModifyType, enumSubjectId } = Enum

// 表单校验规则
const rulesRef = {
  roleName: [
    {
      required: true,
      message: '填写菜单名称',
      trigger: 'blur'
    }
  ]
}

export default {
  components: {
    LayoutDrawerList
  },
  setup () {
    const visible = ref(false)
    const page = ref(1)
    const limit = ref(10)
    const totalCount = ref(0)
    const formRef = ref()
    const drawerType = ref('create')
    const tableList = ref([])
    const { tableTree, allCheckKeys, getMenuList } = mainMenuList
    // 表格配置
    const gridOptions = reactive({
      border: 'inner',
      align: 'center',
      'auto-resize': true,
      'highlight-hover-row': true,
      'max-height': '100%',
      'row-id': 'id',
      'tree-config': { children: 'children' },
      columns: [
        { field: 'roleId', title: 'ID' },
        { field: 'roleName', title: '角色名称' },
        { field: 'remark', title: '备注', showOverflow: true },
        { field: 'createTime', title: '创建时间' },
        { title: '操作', slots: { default: 'modify' } }
      ]
    })
    const defaultModelRef = reactive({
      subjectId: '1',
      roleName: '',
      remark: '0',
      checkedKeys: [],
      menuIdList: []
    })
    const modelRef = ref(defaultModelRef)

    const check = (checkedKeys, event) => {
      modelRef.value.menuIdList = [...event.halfCheckedKeys, ...checkedKeys, '-666666']
    }
    /**
     * 切换页面
     */
    const changePage = () => {
      getRoleList()
    }
    /**
     * 切换每页数量
     */
    const pageSizeChange = () => {
      getRoleList()
    }

    /**
     * 获取角色列表
     */
    const getRoleList = async () => {
      const listRes = await fetchRoleList({ page: page.value, limit: limit.value })
      if (listRes.code === 0) {
        tableList.value = listRes.page.list
        totalCount.value = listRes.page.totalCount
        return
      }
      console.log(listRes)
    }
    /**
     * 提交
     */
    const onSubmit = () => {
      formRef.value.validate().then(async () => {
        let submitRes
        const info = toRaw(modelRef.value)
        if (drawerType.value === 'create') {
          submitRes = await fetchRoleCreate(info)
        } else {
          submitRes = await fetchRoleUpdate(info)
        }
        console.log(submitRes)
        if (submitRes.code === 0) {
          getRoleList()
          visible.value = false
          return
        }
        console.log(submitRes)
      }).catch(err => {
        console.log('error', err)
      })
    }
    /**
     * 提交删除
     */
    const onSubmitDelete = async row => {
      const staticRow = toRaw(row)
      const deleteRes = await fetchRoleDelete([staticRow.roleId])
      console.log(deleteRes)
      if (deleteRes.code === 0) {
        getRoleList()
        return
      }
      console.log(deleteRes)
    }

    /**
     * 切换专题
     */
    const changeSubjectId = async () => {
      formRef.value.resetFields()
      openDrawer(drawerType.value, modelRef.value)
    }
    /**
     * 打开菜单抽屉
     */
    const openDrawer = async (type, row) => {
      if (type === 'create') {
        modelRef.value = defaultModelRef
      } else {
        const infoRes = await fetchRoleInfo({ subjectId: modelRef.value.subjectId, roleId: row.roleId })
        if (infoRes.code === 0) {
          const roleInfo = cloneDeep(infoRes.role)
          delete roleInfo.subjectId
          modelRef.value = { ...modelRef.value, ...roleInfo }
        } else {
          console.log(infoRes)
        }
      }
      await getMenuList(modelRef.value.subjectId, toRaw(modelRef.value.menuIdList))
      modelRef.value.checkedKeys = allCheckKeys
      drawerType.value = type
      visible.value = true
    }

    onMounted(getRoleList())
    return {
      visible,
      page,
      limit,
      totalCount,
      tableList,
      tableTree,
      formRef,
      enumModifyType,
      enumSubjectId,
      drawerType,
      gridOptions,
      labelCol: {
        lg: 9,
        xl: 7,
        xxl: 4
      },
      wrapperCol: {
        lg: 15,
        xl: 17,
        xxl: 20
      },
      modelRef,
      rulesRef,
      changePage,
      pageSizeChange,
      check,
      onSubmit,
      onSubmitDelete,
      changeSubjectId,
      getRoleList,
      openDrawer,
      iconNames: ['AppstoreOutlined', 'AudioOutlined']
    }
  }
}
</script>
